﻿using GalaSoft.MvvmLight.Command;
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Threading;

namespace AutoStar.ViewModel
{
    public class WindowCommandHistoryVM : BaseViewModel
    {
        public event Action DialogClosed;
        public ICommand WindowCommandHistory_Loaded { get; private set; }
        public ICommand WindowCommandHistory_Closing { get; private set; }
        public ICommand ClearHistoryCommand { get; private set; }
        public ICommand SaveHistoryCommand { get; private set; }
        private ObservableCollection<string> _HistoryList;
        public ObservableCollection<string> HistoryList
        {
            get => _HistoryList;
            set => Set(ref _HistoryList, value);
        }
        public WindowCommandHistoryVM()
        {
            HistoryList = new ObservableCollection<string>();
            WindowCommandHistory_Loaded = new RelayCommand(Load);
            WindowCommandHistory_Closing = new RelayCommand(CloseDialog);
            ClearHistoryCommand = new RelayCommand(ClearHistory);
            SaveHistoryCommand = new RelayCommand(SaveHistory);
        }
        public void ClearHistory()
        {
            Global.printer.commandHistory.Clear();
            HistoryList.Clear();
        }
        public void SaveHistory()
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "Text File|*.txt";
            if (saveFileDialog.ShowDialog() == true)
            {
                using (System.IO.StreamWriter file = new System.IO.StreamWriter(saveFileDialog.FileName))
                {
                    foreach (string line in HistoryList)
                    {
                        file.WriteLine(line);
                    }
                }
            }
        }
        public void Load()
        {
            HistoryList = new ObservableCollection<string>();
            for (int i = 0; i < Global.printer.commandHistory.Count(); i++)
            {
                HistoryList.Add(Global.printer.commandHistory[i]);
            }
        }
        public void CloseDialog()
        {
            // 触发事件  
            DialogClosed?.Invoke();
        }
    }
}
